package com.salmon.security.app.social;

import com.salmon.security.core.validate.code.SecurityConstants;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.social.connect.Connection;
import org.springframework.social.connect.ConnectionData;
import org.springframework.social.connect.ConnectionFactoryLocator;
import org.springframework.social.connect.UsersConnectionRepository;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.WebRequest;

import java.util.concurrent.TimeUnit;

/**
 * app环境下替换ProviderSignInUtils，避免由于没有session导致读不到社交用户信息的问题
 *
 */
@Component
public class AppSignUpUtils {

    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;

    @Autowired
    private UsersConnectionRepository usersConnectionRepository;
    @Autowired
    private ConnectionFactoryLocator connectionFactoryLocator;

    /**
     * 缓存社交网站用户信息到Redis
     * @param request
     * @param data
     */
    public void saveConnectionData(WebRequest request, ConnectionData data) {
        redisTemplate.opsForValue().set(getKey(request), data, 10, TimeUnit.MINUTES);
    }

    /**
     * 将缓存的社交网站用户信息与系统注册用户信息进行绑定
     * @param request
     * @param userId
     */
    public void doPostSignUp(WebRequest request, String userId) {
        String key = getKey(request);
        if(!redisTemplate.hasKey(key)) {
            throw new RuntimeException("无法找到缓存的用户社交账户信息");
        }
        ConnectionData connectionData = (ConnectionData)redisTemplate.opsForValue().get(key);
        Connection<?> connection = connectionFactoryLocator
                                                    .getConnectionFactory(connectionData.getProviderId())
                                                    .createConnection(connectionData);
        usersConnectionRepository.createConnectionRepository(userId).addConnection(connection);
        redisTemplate.delete(key);
    }

    private String getKey(WebRequest request) {
      /*  String deviceId = request.getHeader("deviceId");
        if(StringUtils.isBlank(deviceId)) {
            throw new RuntimeException("设备ID不能为空");
        }
        return "salmon:security:social.connect." + deviceId;*/
        String openId = request.getHeader(SecurityConstants.DEFAULT_PARAMETER_NAME_OPENID);
        if(StringUtils.isBlank(openId)) {
            throw new RuntimeException("OpenId不能为空");
        }
        return "salmon:security:social.connect." + openId;
    }
}
